package com.rzjm.api.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.*;
import com.rzjm.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  微信小程序模块
 *@Date 2018-05-10
 */
@Component
@RequestMapping("/edge")//url:模块/资源/{}/细分
public class EdgeController extends BaseController {
    @Resource
    private EdgeRecordService edgeRecordService;
    @Resource
    private UserService userService;
    @Resource
    private DeviceService deviceService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private ShopService shopService;

    @Value("${web.imgprefix}")
    private String imgPrefix;//图片地址

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    //定义⼀个⽅法接收系统推送过的的事件
    //步骤1的地址是 http://ip地址/api/add 和这个地方对应
    @PostMapping("/jk/upload")
    @ResponseBody
    public JSONObject add(@RequestBody String requestParam) {
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
//            System.out.println("jk/upload 接收的参数： " + requestParam);
//            logBefore(logger, "jk/upload 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            System.out.println("接收到盒子的推送");

            int shopId = 178;
            EdgeRecord edgeRecord = JSONUtil.toBean(jsonRequest, EdgeRecord.class);
//            System.out.println("jk/upload 接收的参数： " +edgeRecord.toString());

            if(edgeRecord.getDeviceName().contains("-")){
                String[] name = edgeRecord.getDeviceName().split("-");
                edgeRecord.setDeviceName(name[0]);
                if(StrUtil.isNotEmpty(name[1])){
                    shopId = Integer.parseInt(name[1]);
                    edgeRecord.setShopId(Integer.parseInt(name[1]));
                }
            }else{
                edgeRecord.setShopId(shopId);
            }

            QueryWrapper<Device> qw = new QueryWrapper<>();
            qw.eq("device_num", edgeRecord.getDeviceNum());
            qw.eq("device_type", 7);
            qw.last("limit 1");
            Device device = deviceService.getOne(qw);
            if(device != null){
                edgeRecord.setShopId(device.getShopId());
            }


            Shop shop = shopService.findById(device.getShopId());
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }


//            QueryWrapper<EdgeRecord> qwLast = new QueryWrapper<>();
//            qwLast.eq("shop_id", shopId);
//            qwLast.last("limit 1");
//            EdgeRecord lastRecord = edgeRecordService.getOne(qwLast);
//            if(lastRecord != null){
//                Date checkTime = DateUtil.getAfterSecondsByOld(lastRecord.getCreateTime(), 5 * 60);
//                if (new Date().getTime() < checkTime.getTime()) {
//                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"success"),true,true);
//                }
//            }
            edgeRecord.setCreateTime(new Date());
            try{
                if(StrUtil.isNotEmpty(edgeRecord.getPicUrlBase64())){
                    int upload_type = OssUtil.TYPE_EDGE_RECORD_PHOTOS;
                    String path =  OssUtil.getUploadPrefix(upload_type);
                    String fileName = "edge_record_" + new Date().getTime()  + ".jpg";
                    //D:/webdata/cyh/edge/178
                    Base64Util.generateImage(edgeRecord.getPicUrlBase64(), uploadPath +  path + shopId + "/", fileName);
                    edgeRecord.setPicUrl(path + shopId + "/" + fileName);
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            if(!edgeRecord.getPicUrl().contains("http")){
            }
            edgeRecordService.save(edgeRecord);
            System.out.println("推送记录已添加成功");


            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"success"),true,true);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    //定义⼀个⽅法接收系统推送过的的事件
    //步骤1的地址是 http://ip地址/api/add 和这个地方对应
    @PostMapping("/record/list")
    @ResponseBody
    public JSONObject recordList(@RequestBody String requestParam) {
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("edge/record/list 接收的参数： " + requestParam);
            logBefore(logger, "edge/record/list 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id"): 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;

            List<EdgeRecord> list = new ArrayList<>();
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            Shop shop = shopService.findById(user.getShopId());
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            QueryWrapper<Department> qwDept = new QueryWrapper<>();
            qwDept.eq("company_id", sysUser.getShopId());
            qwDept.eq("dept_type", 1);
            qwDept.last("limit 1");
            Department department = departmentService.getOne(qwDept);
            if(department == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请绑定企业部门"),true,true);
            }


            QueryWrapper<EdgeRecord> qw = new QueryWrapper<>();
            if(user.getIsTest() == 0){
                qw.eq("shop_id", sysUser.getShopId());
            }
            qw.orderByDesc("create_time");
            list = edgeRecordService.getPageEntityList(qw, pageIndex, pageSize);
            if(CollUtil.isNotEmpty(list)){
                for (EdgeRecord record : list){
                    if(StrUtil.isNotEmpty(record.getPicUrl())){
                        record.setPicUrl(imgPrefix + record.getPicUrl());
                    }
                }
            }
            map.put("records", list);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功",list.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


}
